﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ext.Net;
using Viewer.BusinessObject.BusinessEntities;

namespace Viewer.ChucNang.UserControls
{
    public partial class NhomQuyenByModule : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ResourceManager.GetInstance().RegisterIcon(Icon.ApplicationGo);
            }
        }
        private enum DialogType
        {
            AddNew,
            Edit,
            Detail
        }
        protected int NhomQuyenByModuleId
        {
            get
            {
                return int.Parse(this.__NhomQuyenByModuleId.Text);
            }
            set
            {
                this.__NhomQuyenByModuleId.Text = value.ToString();
            }
        }
        public void ShowAddNewDialog()
        {
            SetUpAddNewDialog();
        }

        private void SetUpAddNewDialog()
        {

            this.__DialogType.Text = DialogType.AddNew.ToString();
            this.NhomQuyenByModuleId = 0;
            this.wdNhomQuyenByModule.Title = "Tạo mới nhóm quyền theo chức năng";
            this.wdNhomQuyenByModule.Icon = Icon.Add;

            this.txtTenNhomQuyenByModule.Hidden = false;
            this.txtGhiChu.Hidden = false;

            this.txtTenNhomQuyenByModule.Text = string.Empty;
            this.txtGhiChu.Text = string.Empty;

            this.lblTenNhomQuyenByModule.Text = string.Empty;
            this.lblGhiChu.Text = string.Empty;

            this.storeNguoiDung_NhomQuyenByModule.RemoveAll();
            //grid nguoidung
            btnShowDialogAddNguoiDung.Disabled = false;
            //
            this.txtTenUserOwner.Text = HttpContext.Current.User.Identity.Name;

            ucNguoiDung.BindData();
            BuildTreeModule();
            this.btnSave.Disabled = false;
            wdNhomQuyenByModule.Show();
        }
      
        private void BuildTreeModule()
        {
            List<QUModule> lstModule = new List<QUModule>();
            lstModule = (new QUModule()).GetAll();

            var lstModuleLv1 = (from oModule in lstModule
                                where oModule.ModuleLevel == 1
                                select oModule).ToList();

            TreeNode nodeModule = new TreeNode("Module");
            treeModule.Root.Add(nodeModule);
            nodeModule.Expanded = true;
            foreach (var oModuleLv1 in lstModuleLv1)
            {
                //Create Node
                var nodeLv1 = CreateNode(oModuleLv1);
                nodeModule.Nodes.Add(nodeLv1);

                var lstModuleLv2 = (from oModule in lstModule
                                    where oModule.ModuleIDCha == oModuleLv1.ModuleID
                                    select oModule).ToList();
                if (lstModuleLv2.Count == 0)
                {
                    nodeLv1.Leaf = true;
                }

                foreach (var oModuleLv2 in lstModuleLv2)
                {
                    var nodeLv2 = CreateNode(oModuleLv2);
                    nodeLv1.Nodes.Add(nodeLv2);

                    var lstModuleLv3 = (from oModule in lstModule
                                        where oModule.ModuleIDCha == oModuleLv2.ModuleID
                                        select oModule).ToList();

                    if (lstModuleLv3.Count == 0)
                    {
                        nodeLv2.Leaf = true;
                    }
                    
                    foreach (var oModuleLv3 in lstModuleLv3)
                    {
                        nodeLv2.Nodes.Add(CreateNode(oModuleLv3));
                    }
                }
            }
            //Render to client
            Ext.Net.X.AddScript(string.Format("refreshTree({0},{1});", treeModule.ClientID, treeModule.Root.ToJson()));
        }

        public void ShowEditDialog(int pNhomQuyenByModuleId)
        {
            SetUpEditDialog(pNhomQuyenByModuleId);
        }

        private void SetUpEditDialog(int pNhomQuyenByModuleId)
        {
            this.__DialogType.Text = DialogType.Edit.ToString();
            this.NhomQuyenByModuleId = pNhomQuyenByModuleId;
            this.wdNhomQuyenByModule.Title = "Sửa nhóm quyền theo chức năng";
            this.wdNhomQuyenByModule.Icon = Icon.ApplicationEdit;
            var oQUNhomQuyenByModule = new QUNhomQuyenByModule();
            oQUNhomQuyenByModule = oQUNhomQuyenByModule.GetById(pNhomQuyenByModuleId);
            //Bind data into Detail Area
            this.txtTenNhomQuyenByModule.Hidden = false;
            this.txtGhiChu.Hidden = false;

            this.txtTenNhomQuyenByModule.Text = oQUNhomQuyenByModule.TenNhomQuyenByModule;
            this.txtGhiChu.Text = oQUNhomQuyenByModule.GhiChu;

            this.lblTenNhomQuyenByModule.Text = string.Empty;
            this.lblGhiChu.Text = string.Empty;
            //Grid NguoiDung
            btnShowDialogAddNguoiDung.Disabled = false;
            //
            this.txtTenUserOwner.Text = oQUNhomQuyenByModule.TenUserOwner;

            var oQUNguoiDung = new BusinessObject.BusinessEntities.QUNguoiDung();
            this.storeNguoiDung_NhomQuyenByModule.DataSource = oQUNguoiDung.GetBy_NguoiDungByModuleId(NhomQuyenByModuleId);
            this.storeNguoiDung_NhomQuyenByModule.DataBind();
            ucNguoiDung.BindData();
            BuildTreeModule();
            this.btnSave.Disabled = false;
            wdNhomQuyenByModule.Show();
        }

        public void ShowDetailDialog(int pNhomQuyenByModuleId)
        {
            this.__DialogType.Text = DialogType.Detail.ToString();
            this.NhomQuyenByModuleId = pNhomQuyenByModuleId;
           
            var oQUNhomQuyenByModule = new QUNhomQuyenByModule();
            oQUNhomQuyenByModule = oQUNhomQuyenByModule.GetById(pNhomQuyenByModuleId);
            //Bind data into Detail Area
            this.txtTenNhomQuyenByModule.Hidden = true;
            this.txtGhiChu.Hidden = true;
            this.lblTenNhomQuyenByModule.Text = oQUNhomQuyenByModule.TenNhomQuyenByModule;
            this.lblGhiChu.Text = oQUNhomQuyenByModule.GhiChu;
            //Grid Nguoidung
            this.btnShowDialogAddNguoiDung.Disabled = true;
            //
            var oQUNguoiDung = new BusinessObject.BusinessEntities.QUNguoiDung();
            this.storeNguoiDung_NhomQuyenByModule.DataSource = oQUNguoiDung.GetBy_NguoiDungByModuleId(pNhomQuyenByModuleId);
            this.storeNguoiDung_NhomQuyenByModule.DataBind();

            this.txtTenUserOwner.Text = oQUNhomQuyenByModule.TenUserOwner;

            //ucQUNguoiDung.BindData();
            BuildTreeModule();
            //Hidden Save button

            this.btnSave.Disabled = true;

            this.wdNhomQuyenByModule.Title = "Chi tiết nhóm quyền theo chức năng";
            this.wdNhomQuyenByModule.Icon = Icon.Information;
            this.wdNhomQuyenByModule.Show();
        }

        private TreeNode CreateNode(QUModule oQUModule)
        {

            TreeNode oNode = new TreeNode(oQUModule.ModuleID.ToString(), Icon.ApplicationGo);
            //Bind data to "Is View...
            var oQUNhomQuyenByModule_Module = (from item in this.ListQUNhomQuyenByModule_Module
                                               where item.ModuleID == oQUModule.ModuleID
                                               select item).FirstOrDefault();
            var IsView = false;
            var IsAdd = false;
            var IsEdit = false;
            var IsDelete = false;
            var IsModuleConThuaKe = false;

            if (oQUNhomQuyenByModule_Module != null)
            {
                IsView = oQUNhomQuyenByModule_Module.IsView;
                IsAdd = oQUNhomQuyenByModule_Module.IsAdd;
                IsEdit = oQUNhomQuyenByModule_Module.IsEdit;
                IsDelete = oQUNhomQuyenByModule_Module.IsDelete;
                IsModuleConThuaKe = oQUNhomQuyenByModule_Module.IsModuleConThuaKe;
            }
            //check quyen user tren to chuc do
            QUNhomQuyenByModule_Module quyenByModule = new QUNhomQuyenByModule_Module().GetQuyenByModuleIDandUserID(oQUModule.ModuleID, Viewer.BusinessObject.BusinessEntities.QUNguoiDung.GetByUserName(HttpContext.Current.User.Identity.Name).NguoiDungID);

            oNode.CustomAttributes.Add(new ConfigItem("TenModule", oQUModule.TenModuleFull, ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsView", IsView.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsAdd", IsAdd.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsEdit", IsEdit.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsDelete", IsDelete.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsModuleConThuaKe", IsModuleConThuaKe.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenView", quyenByModule.IsQuyenView.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenAdd", quyenByModule.IsQuyenAdd.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenEdit", quyenByModule.IsQuyenEdit.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsQuyenDelete", quyenByModule.IsQuyenDelete.ToString().ToLower(), ParameterMode.Value));
            oNode.CustomAttributes.Add(new ConfigItem("IsAccess", (IsView && IsAdd && IsEdit && IsDelete).ToString(), ParameterMode.Value));

            oNode.Disabled = !(quyenByModule.IsQuyenAdd || quyenByModule.IsQuyenView || quyenByModule.IsQuyenEdit || quyenByModule.IsQuyenDelete);
            oNode.Expanded = true;
            return oNode;
        }

        private List<QUNhomQuyenByModule_Module> _lstQUNhomQuyenByModule_Module;
        public List<QUNhomQuyenByModule_Module> ListQUNhomQuyenByModule_Module
        {
            get
            {
                if (_lstQUNhomQuyenByModule_Module == null)
                {
                    _lstQUNhomQuyenByModule_Module = (new QUNhomQuyenByModule_Module()).GetByNhomQuyenByModuleId(this.NhomQuyenByModuleId);

                }
                return _lstQUNhomQuyenByModule_Module;
            }
        }

        protected void SubmitNodes(object sender, SubmitEventArgs e)
        {
            if (this.__DialogType.Text == DialogType.AddNew.ToString())
            {
                SaveNewData(e);
                wdNhomQuyenByModule.Hide();
            }
            else if (this.__DialogType.Text == DialogType.Edit.ToString())
            {
                SaveEditData(e);
                wdNhomQuyenByModule.Hide();
            }

        }

        private void SaveEditData(SubmitEventArgs e)
        {
            string[] separator = new string[] { "," };
            var NguoiDungIds = this.__NguoiDungIds.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            //AddNew
            var oQUNhomQuyenByModule = (new BusinessObject.BusinessEntities.QUNhomQuyenByModule()).GetById(this.NhomQuyenByModuleId);
            oQUNhomQuyenByModule.TenNhomQuyenByModule = this.txtTenNhomQuyenByModule.Text.Trim();
            oQUNhomQuyenByModule.GhiChu = this.txtGhiChu.Text.Trim();

            oQUNhomQuyenByModule.QUNhomQuyenByModule_NguoiDungs.Clear();
            foreach (var strId in NguoiDungIds)
            {
                var oNhomQuyenByModule_NguoiDung = new QUNhomQuyenByModule_NguoiDung();
                oNhomQuyenByModule_NguoiDung.NguoiDungID = int.Parse(strId);
                oQUNhomQuyenByModule.QUNhomQuyenByModule_NguoiDungs.Add(oNhomQuyenByModule_NguoiDung);
            }

            var lstNhomQuyenByModule_Module = new List<QUNhomQuyenByModule_Module>();
            ReadNode(e.RootNode, lstNhomQuyenByModule_Module);

            oQUNhomQuyenByModule.QUNhomQuyenByModule_Modules.Clear();

            foreach (var item in lstNhomQuyenByModule_Module)
            {
                oQUNhomQuyenByModule.QUNhomQuyenByModule_Modules.Add(item);
            }
            oQUNhomQuyenByModule.Save();
            ((PagePhanQuyenByModule)this.Page).BindData_NhomQuyenByModule();
        }

        private void SaveNewData(SubmitEventArgs e)
        {
            string[] separator = new string[] { "," };
            var NguoiDungIds = this.__NguoiDungIds.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            //AddNew
            var oQUNhomQuyenByModule = new BusinessObject.BusinessEntities.QUNhomQuyenByModule();
            oQUNhomQuyenByModule.TenNhomQuyenByModule = this.txtTenNhomQuyenByModule.Text.Trim();
            oQUNhomQuyenByModule.UserIDOwner = new Viewer.BusinessObject.BusinessEntities.QUNguoiDung().SearchNguoiDung(this.txtTenUserOwner.Text)[0].NguoiDungID;
            oQUNhomQuyenByModule.TenUserOwner = this.txtTenUserOwner.Text;
            oQUNhomQuyenByModule.GhiChu = this.txtGhiChu.Text.Trim();

            foreach (var strId in NguoiDungIds)
            {
                var oNhomQuyenByModule_NguoiDung = new QUNhomQuyenByModule_NguoiDung();
                oNhomQuyenByModule_NguoiDung.NguoiDungID = int.Parse(strId);
                oQUNhomQuyenByModule.QUNhomQuyenByModule_NguoiDungs.Add(oNhomQuyenByModule_NguoiDung);
            }

            var lstNhomQuyenByModule_Module = new List<QUNhomQuyenByModule_Module>();
            ReadNode(e.RootNode, lstNhomQuyenByModule_Module);
            foreach (var item in lstNhomQuyenByModule_Module)
            {
                oQUNhomQuyenByModule.QUNhomQuyenByModule_Modules.Add(item);
            }
            oQUNhomQuyenByModule.Save();
            //Update GridParent
            //Close window
            ((PagePhanQuyenByModule)this.Page).BindData_NhomQuyenByModule();
        }

        private void ReadNode(SubmittedNode Node, List<QUNhomQuyenByModule_Module> lstItems)
        {

            if (Node.Attributes.Count > 0)
            {
                QUNhomQuyenByModule_Module item = new QUNhomQuyenByModule_Module();
                item.ModuleID = int.Parse(Node.Text);
                item.IsView = bool.Parse(Node.Attributes["IsView"].ToString());
                item.IsAdd = bool.Parse(Node.Attributes["IsAdd"].ToString());
                item.IsEdit = bool.Parse(Node.Attributes["IsEdit"].ToString());
                item.IsDelete = bool.Parse(Node.Attributes["IsDelete"].ToString());
                item.IsModuleConThuaKe = bool.Parse(Node.Attributes["IsModuleConThuaKe"].ToString());

                item.IsQuyenView = bool.Parse(Node.Attributes["IsQuyenView"].ToString());
                item.IsQuyenAdd = bool.Parse(Node.Attributes["IsQuyenAdd"].ToString());
                item.IsQuyenEdit = bool.Parse(Node.Attributes["IsQuyenEdit"].ToString());
                item.IsQuyenDelete = bool.Parse(Node.Attributes["IsQuyenDelete"].ToString());

                if (item.IsView || item.IsAdd || item.IsEdit || item.IsDelete || item.IsModuleConThuaKe)
                {
                    lstItems.Add(item);
                }

            }

            if (Node.Children.Count > 0)
            {
                foreach (var oItem in Node.Children)
                {
                    ReadNode(oItem, lstItems);
                }
            }
        }




    }
}